/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf;



import com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf.config.WapperConfig;
import com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf.source.ContentSource;
import com.fancy.applicaiton.tools.htmltox.wrapper.htmltopdf.source.Source;
import com.fancy.applicaiton.tools.htmltox.wrapper.util.ConfigUtil;
import com.fancy.applicaiton.tools.htmltox.wrapper.util.UUIDUtil;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;

/**
 *
 * @author wison.wu
 */
public class Pdf {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private final WapperConfig wapperConfig;

    public Pdf(){
        wapperConfig = new WapperConfig();
    }

    /**
     * 保存
     * @return 
     */
    public String save(){
        String destPath = getFullPath();
        File file = new File(destPath);
        File parent = file.getParentFile();
        //如果pdf保存路径不存在，则创建路径
        if(!parent.exists()){
            parent.mkdirs();
        }
        String command = wapperConfig.getCommmand();
        command +=" "+destPath;
        Boolean flag = generatePdf(command);
        if(!flag)destPath="";
        return destPath;
    }

    private String getFullPath(){
        String savePath = ConfigUtil.getAppConfig("pdf.save.path");
        return savePath+ "/"+ UUIDUtil.random()+".pdf";
    }

    public void addSource(Source<?>...sources){
        for (Source<?> source : sources) {
            wapperConfig.getSourceList().add(source);
        }
    }
    
    
    /**
     * 根据命令生成pdf
     * @param command
     * @return 
     */
    private Boolean generatePdf(String command){
        Boolean flag = Boolean.TRUE;
        try{
            Process proc = Runtime.getRuntime().exec(command);
            HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
            HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
            error.start();
            output.start();
            proc.waitFor();
        }catch(IOException | InterruptedException e){
            flag = Boolean.FALSE;
            logger.error("转换服务执行错误，命令为:  "+command+"  异常信息为:  "+e);
        }finally {
           deleteTempFile();
        }
        return flag;
    }

    /**
     * 删除临时文件
     */
    private void deleteTempFile() {
    wapperConfig.getSourceList().forEach(source -> {
        if(source instanceof ContentSource){
            ContentSource contentSource = (ContentSource)source;
            new File(contentSource.getSource()).delete();
        }
    });
    }

//    public static void main(String[] args) {
//        Pdf pdf = new Pdf();
//        pdf.addSource(new UrlSource("http://www.qq.com"));
//        pdf.addSource(new UrlSource("http://www.163.com"));
//        pdf.save("h:/test.pdf");
//    }
}
